package org.jeecg.modules.bus.controller;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.annotation.ApiLogin;
import org.jeecg.com.util.ThirdSessionHolder;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.TenantContextHolder;
import org.jeecg.config.ApiVersion;
import org.jeecg.config.ApiVersionConstant;
import org.jeecg.config.WebConfig;
import org.jeecg.modules.bus.vo.CesStockTypeVo;
import org.jeecg.modules.business.dto.BookingLayoutRoomsDto;
import org.jeecg.modules.business.dto.BookingOrderSaveDto;
import org.jeecg.modules.business.dto.KedanOrderDto;
import org.jeecg.modules.business.entity.*;
import org.jeecg.modules.business.enums.CheckInTypeEnum;
import org.jeecg.modules.business.service.*;
import org.jeecg.modules.business.service.impl.BusMarketMemberServiceImpl;
import org.jeecg.modules.business.service.impl.BusRoomPayTypeServiceImpl;
import org.jeecg.modules.business.vo.KeLiItemVo;
import org.jeecg.modules.mall.entity.*;
import org.jeecg.modules.mall.service.*;
import org.jeecg.modules.order.entity.CesOrderComment;
import org.jeecg.modules.order.service.impl.CesOrderCommentServiceImpl;
import org.jeecg.modules.pos.entity.PosTable;
import org.jeecg.modules.pos.entity.PosType;
import org.jeecg.modules.pos.service.IPosTableService;
import org.jeecg.modules.pos.service.IPosTypeService;
import org.jeecg.modules.rooms.DTO.CanUseRequestParamDto;
import org.jeecg.modules.rooms.Vo.CanUseResultVo;
import org.jeecg.modules.rooms.entity.*;
import org.jeecg.modules.rooms.service.*;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wxuser.service.IUserInfoService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 酒店列表
 */
@Api(tags="酒店列表")
@RestController
@AllArgsConstructor
@RequestMapping("/mall-api/hotel")
@Slf4j
public class HotelController extends WebConfig {
    @Resource
    private IBusHotelService busHotelService;
    @Resource
    private CesRoomLayoutServiceImpl cesRoomLayoutService;
    @Resource
    private CesRoomsServiceImpl cesRoomsService;
    @Resource
    private CesOrderCommentServiceImpl cesOrderCommentService;
    @Resource
    private IBusRoomBookingOrdersService busRoomBookingOrdersService;
    @Resource
    private IBusMemberCardService busMemberCardService;
    @Resource
    private IBusRoomsLivingOrderService busRoomsLivingOrderService;
    @Resource
    private IBusBookingRoomsService busBookingRoomsService;
    @Resource
    private CesRoomLayoutPriceServiceImpl cesRoomLayoutPriceService;
    @Resource
    private IMallHotelOrderService mallHotelOrderService;
    @Resource
    private IBusMarketCouponsCashUsedService busMarketCouponsCashUsedService;
    @Resource
    private IBusMarketCouponsCashService busMarketCouponsCashService;
    @Resource
    private IUserInfoService userInfoService;
    @Resource
    private IBusDictItemService busDictItemService;
    @Resource
    private CesHourRoomRuleServiceImpl cesHourRoomRuleService;
    @Resource
    private CesGoodsServiceImpl cesGoodsService;
    @Resource
    private CesStockTypeServiceImpl cesStockTypeService;
    @Resource
    private IMallOrderGoodsService mallOrderGoodsService;
    @Resource
    private IMallOrderGoodsDetailService mallOrderGoodsDetailService;
    @Resource
    private IBusMemberBalanceLogService busMemberBalanceLogService;
    @Resource
    private ISysBaseAPI sysBaseAPI;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private BusRoomPayTypeServiceImpl busRoomPayTypeService;
    @Resource
    private IBusLivingCustomerService busLivingCustomerService;
    @Resource
    private IBusMarketMemberService busMarketMemberService;
    @Resource
    private IMallPosTableOrderGoodsService mallPosTableOrderGoodsService;
    @Resource
    private IMallPosTableOrderGoodsDetailService mallPosTableOrderGoodsDetailService;
    @Resource
    private IPosTableService posTableService;
    @Resource
    private IPosTypeService posTypeService;
    /**
     * 酒店列表查询
     *
     * @param busHotel
     * @param req
     * @return
     */
    @ApiOperation(value = "酒店列表查询", notes = "酒店列表查询")
    @GetMapping(value = "/queryList")
    @ApiLogin
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    public Result<List<BusHotel>> queryList(BusHotel busHotel, HttpServletRequest req) {
        QueryWrapper<BusHotel> queryWrapper = QueryGenerator.initQueryWrapper(busHotel, req.getParameterMap());
        String tenantId = TenantContextHolder.getTenantId();
        if (StringUtils.isNotBlank(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        queryWrapper.eq("status", 1);
        queryWrapper.eq("check_status", 1);
        queryWrapper.eq("del_flag", 0);
        List<BusHotel> list = busHotelService.list(queryWrapper);
        return Result.OK(list);
    }

    /**
     * 可入住酒店列表
     *
     * @param pageNo
     * @param pageSize
     * @param sort     0推荐排序 1 距离优先 2低价优先 3评分优先 4评论数优先
     * @param keyWord  搜索关键字
     * @return
     */
    @ApiOperation(value = "可入住酒店列表", notes = "可入住酒店列表")
    @GetMapping(value = "/can-use-hotel-list")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    public Result<IPage<BusHotel>> getCanUseHotelList(HttpServletRequest request,@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      @RequestParam(name = "sort", defaultValue = "0") Integer sort,
                                                      @RequestParam(name = "city", defaultValue = "") String city,
                                                      @RequestParam(name = "keyWord", defaultValue = "") String keyWord,
                                                      @RequestParam(name = "lat", defaultValue = "0") BigDecimal lat,
                                                      @RequestParam(name = "lng", defaultValue = "0") BigDecimal lng) {
        Page<BusHotel> page = new Page<BusHotel>(pageNo, pageSize);
        String tenantId = TenantContextHolder.getTenantId();
        if (StringUtils.isBlank(tenantId))
            tenantId = request.getHeader("tenant-id");
        IPage<BusHotel> pageList = busHotelService.pageList(page, tenantId, city, keyWord, sort, lat, lng);
        return Result.OK(pageList);
    }

    /**
     * 通过id查询酒店详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过id查询酒店详情", notes = "通过id查询酒店详情")
    @GetMapping(value = "/queryById")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    public Result<BusHotel> queryById(@RequestParam(name = "id", required = true) String id) {
        BusHotel busHotel = busHotelService.getById(id);
        LambdaQueryWrapper<CesOrderComment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CesOrderComment::getHotelId, busHotel.getId());
        lambdaQueryWrapper.eq(CesOrderComment::getCommentType, 1);
        List<CesOrderComment> list = cesOrderCommentService.list(lambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(list)) {
            busHotel.setCommentNum(list.size());
            Double score = list.stream().collect(Collectors.averagingDouble(CesOrderComment::getScore));
            busHotel.setScore(score);
        }
        return Result.OK(busHotel);
    }

    /**
     * 根据酒店查询房型对应可用房间
     *
     * @param param
     * @return
     */
    @ApiOperation(value = "根据酒店查询房型对应可用房间", notes = "根据酒店查询房型对应可用房间")
    @GetMapping(value = "/can-user-rooms")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    public Result<List<CanUseResultVo>> getCanUseRooms(CanUseRequestParamDto param) {
        if (param.getHotelId() == null || param.getHotelId().isEmpty())
            throw new JeecgBootException("参数错误");
        if (param.getEndOf() == null || param.getStartOf() == null)
            throw new JeecgBootException("请传入时间范围");
        if (param.getBookingType().equals(CheckInTypeEnum.HOUR_TIME.getKey())) {
            LambdaQueryWrapper<CesHourRoomRule> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(CesHourRoomRule::getHotelId, param.getHotelId());
            lambdaQueryWrapper.orderByAsc(CesHourRoomRule::getAfterOpenRoom).last("limit 1");
            CesHourRoomRule cesHourRoomRule = cesHourRoomRuleService.getOne(lambdaQueryWrapper);
            if (cesHourRoomRule != null) {
                param.setHourRoomRuleId(cesHourRoomRule.getId());
            }
        }
        return Result.ok(cesRoomsService.getCanUseRooms(param));
    }


    /**
     * 根据酒店查询评价列表
     *
     * @param cesOrderComment
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "根据酒店查询评价列表", notes = "根据酒店查询评价列表")
    @GetMapping(value = "/comment-list")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    public Result<IPage<CesOrderComment>> getCommentPageList(CesOrderComment cesOrderComment,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                             HttpServletRequest req) {
        LambdaQueryWrapper<CesOrderComment> queryWrapper = QueryGenerator.initQueryWrapper(cesOrderComment, req.getParameterMap()).lambda();
        Page<CesOrderComment> page = new Page<CesOrderComment>(pageNo, pageSize);
        IPage<CesOrderComment> pageList = cesOrderCommentService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


//    /**
//     * 酒店预定订单添加
//     *
//     * @param busRoomBookingOrders
//     * @return
//     */
//    @AutoLog(value = "酒店预定订单-添加")
//    @ApiOperation(value = "酒店预定订单-添加", notes = "酒店预定订单-添加")
//    @PostMapping(value = "/hotel-room-booking")
//    @ApiLogin
//    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
//    public Result<String> hotelRoomBookingAdd(@RequestBody BookingOrderSaveDto busRoomBookingOrders) {
//        Boolean isTeam = busRoomBookingOrders.getOrderInfo().getBookingOrdersType().equals(2);
//        busRoomBookingOrders.getOrderInfo().setBookingOrdersType(1);
//        String tenantId = TenantContextHolder.getTenantId();
//        String userId = ThirdSessionHolder.getUserId();
//        busRoomBookingOrders.getOrderInfo().setThirdLoginUserId(userId);
//        LambdaQueryWrapper<BusMemberCard> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(BusMemberCard::getUserId, userId);
//        lambdaQueryWrapper.eq(BusMemberCard::getHotelId, busRoomBookingOrders.getHotelId()).last("limit 1");
//        BusMemberCard busMemberCard = busMemberCardService.getOne(lambdaQueryWrapper);
//        if (busMemberCard != null) {
//            busRoomBookingOrders.getOrderInfo().setCustomerType(2);
//            busRoomBookingOrders.getOrderInfo().setVipCustomerId(busMemberCard.getId());
//        } else {
//            busRoomBookingOrders.getOrderInfo().setCustomerType(1);
//        }
//        return Result.OK("预定成功", busRoomBookingOrdersService.bookingOrderSave(busRoomBookingOrders, isTeam));
//    }

    /**
     * 生成16位数字+prefix
     *
     * @param prefix
     * @return
     */
    private String randomNumber(String prefix) {
        int first = new Random(10).nextInt(8) + 1;
        int hashCode = UUID.randomUUID().toString().hashCode();
        if (hashCode < 0) {
            hashCode = -hashCode;
        }
        return prefix + first + String.format("%015d", hashCode);
    }

    @AutoLog(value = "酒店预定订单-添加")
    @ApiOperation(value = "酒店预定订单-添加", notes = "酒店预定订单-添加")
    @PostMapping(value = "/hotel-order")
    @ApiLogin
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @Transactional(rollbackFor = Exception.class)
    public Result<String> hotelOrderAdd(@RequestBody MallHotelOrder mallHotelOrder) {
        String tenantId = TenantContextHolder.getTenantId();
        String userId = ThirdSessionHolder.getUserId();
        MallUserInfo mallUserInfo = userInfoService.getById(userId);
        BigDecimal couponMoney = BigDecimal.ZERO;
        if (StringUtils.isNotBlank(mallHotelOrder.getCouponId())) {
            BusMarketCouponsCashUsed busMarketCouponsCashUsed = busMarketCouponsCashUsedService.getById(mallHotelOrder.getCouponId());
            if (ObjectUtils.isEmpty(busMarketCouponsCashUsed)) {
                return Result.error("优惠券不存在");
            }
            if (!busMarketCouponsCashUsed.getUserid().equals(userId) && !busMarketCouponsCashUsed.getMobile().equals(mallUserInfo.getMobile())) {
                return Result.error("优惠券非法使用");
            }
            BusMarketCouponsCash coupons = busMarketCouponsCashService.getById(busMarketCouponsCashUsed.getCouponsId());
            if (ObjectUtils.isEmpty(coupons)) {
                return Result.error("优惠券活动不存在");
            }
            mallHotelOrder.setCouponMoney(coupons.getCost());
            busMarketCouponsCashUsed.setStatus(2);
            busMarketCouponsCashUsed.setUsedTime(DateTime.now());
            busMarketCouponsCashUsedService.updateById(busMarketCouponsCashUsed);
            couponMoney = coupons.getCost();
        }
        mallHotelOrder.setTenantId(tenantId);
        mallHotelOrder.setMallUserId(userId);
        mallHotelOrder.setCreateTime(DateTime.now());
        String prefix = "YD";
        mallHotelOrder.setCode(randomNumber(prefix));
        mallHotelOrder.setPayType(1);
        mallHotelOrder.setStatus(5);

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date four = null;
        try {
            four = formatter2.parse(formatter.format(mallHotelOrder.getStartDate()) + " " + mallHotelOrder.getArriveTime());
            mallHotelOrder.setStartDate(four);
        } catch (ParseException e) {

        }
        CesHourRoomRule cesHourRoomRule = null;
        Calendar calendar = new GregorianCalendar();
        if (mallHotelOrder.getBookingType().equals(2)) {
            CesRoomLayoutPrice cesRoomLayoutPrice = cesRoomLayoutPriceService.getById(mallHotelOrder.getRoomLayoutPriceId());
            cesHourRoomRule = cesHourRoomRuleService.getById(cesRoomLayoutPrice.getSellerId());
            calendar.setTime(mallHotelOrder.getStartDate());
            calendar.add(Calendar.MINUTE, cesHourRoomRule.getAfterOpenRoom());
            mallHotelOrder.setEndDate(calendar.getTime());
        }
        log.info("getStartDate---------------" + mallHotelOrder.getStartDate());
        log.info("getEndDate---------------" + mallHotelOrder.getEndDate());
        mallHotelOrderService.save(mallHotelOrder);

        //增加临时坑位预定单
        BookingOrderSaveDto busRoomBookingOrders = new BookingOrderSaveDto();
        busRoomBookingOrders.setContactName(mallHotelOrder.getContactName());
        busRoomBookingOrders.setHotelId(mallHotelOrder.getHotelId());
        busRoomBookingOrders.setPhone(mallHotelOrder.getMobile());

        List<BusBookingLayoutDayPrice> layoutDayPrices = new ArrayList<>();
        long getTime = mallHotelOrder.getEndDate().getTime() - mallHotelOrder.getStartDate().getTime();
        long day = getTime / (1000 * 60 * 60 * 24);
        if (day == 0) {
            day = 1;
        }
        log.info("day---------------" + day);
        BigDecimal sCouponMoney = couponMoney;
        for (Integer i = 0; i < day; i++) {
            calendar.setTime(mallHotelOrder.getStartDate());
            calendar.add(Calendar.DATE, i);

            BusBookingLayoutDayPrice busBookingLayoutDayPrice = new BusBookingLayoutDayPrice();
            busBookingLayoutDayPrice.setBookingType(1);
            busBookingLayoutDayPrice.setDayTime(calendar.getTime());
            BigDecimal sum = mallHotelOrder.getDayMoney().subtract(sCouponMoney);
            if (sum.compareTo(BigDecimal.ZERO) < 0) {
                sCouponMoney = sum;
                sum = BigDecimal.ZERO;
            }
            busBookingLayoutDayPrice.setPrice(sum);
            busBookingLayoutDayPrice.setRoomLayoutId(mallHotelOrder.getLayoutId());
            layoutDayPrices.add(busBookingLayoutDayPrice);
        }
        busRoomBookingOrders.setLayoutDayPrices(layoutDayPrices);

        BusRoomBookingOrders bookingOrders = new BusRoomBookingOrders();
        bookingOrders.setArrivalTime(mallHotelOrder.getStartDate());
        LambdaQueryWrapper<BusDictItem> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(BusDictItem::getHotelId, mallHotelOrder.getHotelId());
        lambdaQueryWrapper2.eq(BusDictItem::getDictId, "1639544187093995521");
        List<BusDictItem> busDictItems = busDictItemService.list(lambdaQueryWrapper2);
        if (ObjectUtils.isNotEmpty(busDictItems)) {
            bookingOrders.setBookingDicWay(busDictItems.get(0).getId());
        }
        bookingOrders.setBookingOrdersType(1);
        bookingOrders.setBreakfastNum(0);

        lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(BusDictItem::getHotelId, mallHotelOrder.getHotelId());
        lambdaQueryWrapper2.eq(BusDictItem::getDictId, "1639538915239743490");
        busDictItems = busDictItemService.list(lambdaQueryWrapper2);
        if (ObjectUtils.isNotEmpty(busDictItems)) {
            Optional<BusDictItem> busDictItemOptional = busDictItems.stream().filter(t -> t.getItemText().equals("微信订房")).findFirst();
            if (busDictItemOptional.isPresent()) {
                bookingOrders.setCustomerSource(busDictItemOptional.get().getId());
            } else {
                bookingOrders.setCustomerSource(busDictItems.get(0).getId());
            }
        }
        bookingOrders.setCustomerType(1);
        bookingOrders.setDayCount(mallHotelOrder.getDay());
        bookingOrders.setDueOutTime(mallHotelOrder.getEndDate());
        bookingOrders.setWarrantType(1);
        bookingOrders.setOuterOrdersNo(mallHotelOrder.getCode());
        bookingOrders.setBookingStatus(3);
        bookingOrders.setBookingType(mallHotelOrder.getBookingType());
        if (mallHotelOrder.getBookingType().equals(2)) {
            bookingOrders.setHourRoomId(cesHourRoomRule.getId());
        }
        busRoomBookingOrders.setOrderInfo(bookingOrders);

        List<BookingLayoutRoomsDto> roomIds = new ArrayList<>();
        BookingLayoutRoomsDto bookingLayoutRoomsDto = new BookingLayoutRoomsDto();
        bookingLayoutRoomsDto.setLayoutId(mallHotelOrder.getLayoutId());
        bookingLayoutRoomsDto.setRoomId(null);
        roomIds.add(bookingLayoutRoomsDto);
        busRoomBookingOrders.setRoomIds(roomIds);

        Boolean isTeam = busRoomBookingOrders.getOrderInfo().getBookingOrdersType().equals(2);
        busRoomBookingOrders.getOrderInfo().setBookingOrdersType(1);
        busRoomBookingOrders.getOrderInfo().setThirdLoginUserId(userId);
        LambdaQueryWrapper<BusMemberCard> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BusMemberCard::getUserId, userId);
        lambdaQueryWrapper.eq(BusMemberCard::getHotelId, busRoomBookingOrders.getHotelId()).last("limit 1");
        BusMemberCard busMemberCard = busMemberCardService.getOne(lambdaQueryWrapper);
        if (busMemberCard != null) {
            busRoomBookingOrders.getOrderInfo().setCustomerType(2);
            busRoomBookingOrders.getOrderInfo().setVipCustomerId(busMemberCard.getId());
        } else {
            busRoomBookingOrders.getOrderInfo().setCustomerType(1);
        }
        busRoomBookingOrdersService.bookingOrderSave(busRoomBookingOrders, isTeam,false,mallHotelOrder.getHotelId());

        //创建业务消息信息
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper3.eq(SysUser::getDelFlag, 0);
        lambdaQueryWrapper3.eq(SysUser::getRelTenantIds, mallHotelOrder.getTenantId());
        List<SysUser> sysUsers = sysUserService.list(lambdaQueryWrapper3);
        String userIds = "";
        for (SysUser sysUser : sysUsers) {
            userIds += sysUser.getUsername() + ",";
        }
        if (userIds.length() > 0) {
            MessageDTO messageDTO = new MessageDTO();
            messageDTO.setFromUser("");
            messageDTO.setToUser(userIds);
            messageDTO.setTitle("用户预定了酒店订单");
            messageDTO.setContent("用户预定了酒店订单");
            messageDTO.setCategory(CommonConstant.MSG_CATEGORY_2);
            sysBaseAPI.sendSysAnnouncement(messageDTO);
        }
        return Result.OK("预定成功");
    }


    /**
     * 预定/入住订单列表
     *
     * @param type          1 入住订单查询->livingStatus | 2 bookingStatus
     * @param livingStatus  -1 正常入住，1 已结账退房，2 先走未结,3 联房退房
     * @param bookingStatus 1 预定中 2 在住 3 已取消
     * @return
     */
    @ApiOperation(value = "预定/入住订单列表", notes = "预定/入住订单列表")
    @RequestMapping(value = "/kedan-orders", method = RequestMethod.GET)
    @ApiLogin
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    public Result<IPage<KeLiItemVo>> keli(Page<KeLiItemVo> page, KedanOrderDto kedanOrderDto) {
        if (kedanOrderDto.getType() == null) throw new JeecgBootException("参数错误");
        if (kedanOrderDto.getType() == 1 && kedanOrderDto.getLivingStatus() == null) throw new JeecgBootException("参数错误");
        if (kedanOrderDto.getType() == 2 && kedanOrderDto.getBookingStatus() == null) throw new JeecgBootException("参数错误");
        kedanOrderDto.setThirdUserId(ThirdSessionHolder.getUserId());
        if (kedanOrderDto.getType() == 1)
            return Result.OK(busRoomBookingOrdersService.getLivingOrderKL(page, kedanOrderDto));
        if (kedanOrderDto.getType() == 2)
            return Result.OK(busRoomBookingOrdersService.getBookingOrderKL(page, kedanOrderDto));
        return null;
    }

    /**
     * 查询已入住酒店信息
     *
     * @return
     */
    @ApiOperation(value = "查询已入住酒店信息", notes = "查询已入住酒店信息")
    @GetMapping(value = "/living-hotel-info")
    @ApiLogin
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    public Result<BusHotel> getLivingInfo() {
        BusHotel busHotel = null;
        String tenantId = TenantContextHolder.getTenantId();
        String userId = ThirdSessionHolder.getUserId();
        LambdaQueryWrapper<BusRoomsLivingOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BusRoomsLivingOrder::getSettleType,-1);
        lambdaQueryWrapper.eq(BusRoomsLivingOrder::getThirdLoginUserId, userId).orderByDesc(BusRoomsLivingOrder::getCreateTime).last("limit 1");
        BusRoomsLivingOrder busRoomsLivingOrder = busRoomsLivingOrderService.getOne(lambdaQueryWrapper);
        if (busRoomsLivingOrder != null && StringUtils.isNotBlank(busRoomsLivingOrder.getBookingOrderId())) {
            LambdaQueryWrapper<BusBookingRooms> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(BusBookingRooms::getBookingOrdersId, busRoomsLivingOrder.getBookingOrderId()).last("limit 1");
            BusBookingRooms bookingRooms = busBookingRoomsService.getOne(lambdaQueryWrapper1);
            if (bookingRooms != null) {
                CesRooms cesRooms = cesRoomsService.getById(bookingRooms.getRoomId());
                if (cesRooms != null) {
                    busHotel = busHotelService.getById(cesRooms.getHotelId());
                    busHotel.setRoomName(cesRooms.getName());
                    CesRoomLayout cesRoomLayout = cesRoomLayoutService.getById(cesRooms.getLayoutId());
                    busHotel.setCesRoomLayout(cesRoomLayout);
                    busHotel.setLivingOrder(busRoomsLivingOrder);
                    LambdaQueryWrapper<BusLivingCustomer> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper2.eq(BusLivingCustomer::getLivingOrderId, busRoomsLivingOrder.getId());
                    List<BusLivingCustomer> livingCustomers = busLivingCustomerService.list(lambdaQueryWrapper2);
                    if (livingCustomers != null && livingCustomers.size() > 0) {
                        busHotel.setBusLivingCustomer(livingCustomers.get(0));
                    }
                }
            }
        }
        return Result.ok(busHotel);
    }

    /**
     * 根据房型查询对应房价列表
     *
     * @param layoutId
     * @return
     */
    @ApiOperation(value = "根据房型查询对应房价列表", notes = "根据房型查询对应房价列表")
    @GetMapping(value = "/room-layout-price")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    public Result<List<CesRoomLayoutPrice>> getRoomLayoutPrice(@RequestParam(name = "layoutId", required = true) String layoutId, @RequestParam(name = "type", required = true) Integer type) {
        LambdaQueryWrapper<CesRoomLayoutPrice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CesRoomLayoutPrice::getLayoutId, layoutId);
        lambdaQueryWrapper.eq(CesRoomLayoutPrice::getType, type);
        List<CesRoomLayoutPrice> list = cesRoomLayoutPriceService.list(lambdaQueryWrapper);
        return Result.ok(list);
    }

    /**
     * 酒店预定订单列表
     *
     * @param mallHotelOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "酒店预定订单列表", notes = "酒店预定订单列表")
    @GetMapping(value = "/hotel_order-list")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<IPage<MallHotelOrder>> getHotelOrderPageList(MallHotelOrder mallHotelOrder,
                                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                               HttpServletRequest req) {
        String tenantId = TenantContextHolder.getTenantId();
        String userId = ThirdSessionHolder.getUserId();
        LambdaQueryWrapper<MallHotelOrder> queryWrapper = QueryGenerator.initQueryWrapper(mallHotelOrder, req.getParameterMap()).lambda();
        queryWrapper.eq(MallHotelOrder::getTenantId, tenantId);
        queryWrapper.eq(MallHotelOrder::getMallUserId, userId);
        Page<MallHotelOrder> page = new Page<MallHotelOrder>(pageNo, pageSize);
        IPage<MallHotelOrder> pageList = mallHotelOrderService.page(page, queryWrapper);
        pageList.getRecords().forEach(t -> {
            if (t.getStatus().equals(1)) {
                t.setStatusName("未付款");
            } else if (t.getStatus().equals(2)) {
                t.setStatusName("已付款");
            } else if (t.getStatus().equals(3)) {
                t.setStatusName("已取消");
            } else if (t.getStatus().equals(4)) {
                t.setStatusName("已完成");
            } else if (t.getStatus().equals(5)) {
                t.setStatusName("待入住");
            } else if (t.getStatus().equals(6)) {
                t.setStatusName("已入住");
            } else if (t.getStatus().equals(7)) {
                t.setStatusName("退款中");
            }
            BusHotel hotel = busHotelService.getById(t.getHotelId());
            if (hotel != null) {
                t.setHotelName(hotel.getName());
            }
            CesRoomLayout layout = cesRoomLayoutService.getById(t.getLayoutId());
            if (layout != null) {
                t.setLayoutName(layout.getName());
            }
        });
        return Result.OK(pageList);
    }

    @ApiOperation(value = "酒店订单确认入住", notes = "酒店订单确认入住")
    @PostMapping(value = "/confirm-move")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<String> confirmMove(@RequestBody MallHotelOrder mallHotelOrder) {
        MallHotelOrder order = mallHotelOrderService.getById(mallHotelOrder.getId());
        if (!order.getStatus().equals(5)) {
            return Result.error("订单不是待入住状态");
        }
        order.setStatus(6);
        mallHotelOrderService.updateById(order);

        LambdaUpdateWrapper<BusRoomBookingOrders> updateWrapper = new UpdateWrapper().lambda();
        updateWrapper.set(BusRoomBookingOrders::getBookingStatus, 1);
        updateWrapper.eq(BusRoomBookingOrders::getOuterOrdersNo, order.getCode());
        busRoomBookingOrdersService.update(updateWrapper);
        //创建业务消息信息
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getDelFlag, 0);
        lambdaQueryWrapper.eq(SysUser::getRelTenantIds, order.getTenantId());
        List<SysUser> sysUsers = sysUserService.list(lambdaQueryWrapper);
        String userIds = "";
        for (SysUser sysUser : sysUsers) {
            userIds += sysUser.getUsername() + ",";
        }
        if (userIds.length() > 0) {
            MessageDTO messageDTO = new MessageDTO();
            messageDTO.setFromUser("");
            messageDTO.setToUser(userIds);
            messageDTO.setTitle("酒店订单确认入住");
            messageDTO.setContent("用户已确认酒店订单入住");
            messageDTO.setCategory(CommonConstant.MSG_CATEGORY_2);
            sysBaseAPI.sendSysAnnouncement(messageDTO);
        }
        return Result.OK("确认入住成功！");
    }

    @ApiOperation(value = "酒店订单取消", notes = "酒店订单取消")
    @PostMapping(value = "/confirm-cancel")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<String> confirmCancel(@RequestBody MallHotelOrder mallHotelOrder) {
        MallHotelOrder order = mallHotelOrderService.getById(mallHotelOrder.getId());
        if (order.getStatus().equals(4) || order.getStatus().equals(6)) {
            return Result.error("订单已完成/已入住状态");
        }
        order.setStatus(3);
        mallHotelOrderService.updateById(order);
        //创建业务消息信息
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getDelFlag, 0);
        lambdaQueryWrapper.eq(SysUser::getRelTenantIds, order.getTenantId());
        List<SysUser> sysUsers = sysUserService.list(lambdaQueryWrapper);
        String userIds = "";
        for (SysUser sysUser : sysUsers) {
            userIds += sysUser.getUsername() + ",";
        }
        if (userIds.length() > 0) {
            MessageDTO messageDTO = new MessageDTO();
            messageDTO.setFromUser("");
            messageDTO.setToUser(userIds);
            messageDTO.setTitle("商城酒店订单取消");
            messageDTO.setContent("用户已确认商城酒店订单取消");
            messageDTO.setCategory(CommonConstant.MSG_CATEGORY_2);
            sysBaseAPI.sendSysAnnouncement(messageDTO);
        }
        return Result.OK("取消成功！");
    }

    /**
     * 通过id查询酒店预定订单详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过id查询酒店预定订单详情", notes = "通过id查询酒店预定订单详情")
    @GetMapping(value = "/hotel_order-info")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<MallHotelOrder> getHotelOrderInfo(@RequestParam(name = "id", required = true) String id) {
        MallHotelOrder mallHotelOrder = mallHotelOrderService.getById(id);
        if (mallHotelOrder == null) {
            return Result.error("未找到对应数据");
        }
        log.info("mallHotelOrder--------" + mallHotelOrder.toString());
        String userId = ThirdSessionHolder.getUserId();
        log.info("userId--------" + userId);
        if (!mallHotelOrder.getMallUserId().equals(userId)) {
            return Result.error("未找到对应数据");
        }
        BusHotel hotel = busHotelService.getById(mallHotelOrder.getHotelId());
        mallHotelOrder.setHotel(hotel);
        if (mallHotelOrder.getStatus().equals(1)) {
            mallHotelOrder.setStatusName("未付款");
        } else if (mallHotelOrder.getStatus().equals(2)) {
            mallHotelOrder.setStatusName("已付款");
        } else if (mallHotelOrder.getStatus().equals(3)) {
            mallHotelOrder.setStatusName("已取消");
        } else if (mallHotelOrder.getStatus().equals(4)) {
            mallHotelOrder.setStatusName("已完成");
        } else if (mallHotelOrder.getStatus().equals(5)) {
            mallHotelOrder.setStatusName("待入住");
        } else if (mallHotelOrder.getStatus().equals(6)) {
            mallHotelOrder.setStatusName("已入住");
        } else if (mallHotelOrder.getStatus().equals(7)) {
            mallHotelOrder.setStatusName("退款中");
        }
        CesRoomLayout layout = cesRoomLayoutService.getById(mallHotelOrder.getLayoutId());
        if (layout != null) {
            mallHotelOrder.setLayoutName(layout.getName());
        }
        if (StringUtils.isNotBlank(mallHotelOrder.getCouponId())) {
            BusMarketCouponsCash busMarketCouponsCash = busMarketCouponsCashService.getById(mallHotelOrder.getCouponId());
            if (busMarketCouponsCash != null) {
                mallHotelOrder.setCouponName(busMarketCouponsCash.getName());
            }
        }
        return Result.OK(mallHotelOrder);
    }

    /**
     * 根据类型分组外卖商品列表
     *
     * @param cesGoods
     * @return
     */
    @ApiOperation(value = "根据类型分组外卖商品列表", notes = "根据类型分组外卖商品列表")
    @GetMapping(value = "/type_group_goods_list")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<List<CesStockTypeVo>> queryPageList(CesGoods cesGoods) {
        List<CesStockType> list = cesStockTypeService.list(Wrappers.<CesStockType>lambdaQuery()
                .eq(CesStockType::getHotelId, cesGoods.getHotelId())
                .eq(CesStockType::getInvalid, false)
                .like(CesStockType::getApplyScope, "1"));
        List<CesStockTypeVo> voList = new ArrayList<>();
        List<CesStockType> pList = list.stream().filter(t -> StringUtils.isBlank(t.getParentId()) || t.getParentId().equals("0")).collect(Collectors.toList());
        pList.forEach(t -> {
            CesStockTypeVo vo = new CesStockTypeVo();
            vo.setName(t.getName());
            LambdaQueryWrapper<CesGoods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CesGoods::getInvalid, false);
            queryWrapper.eq(CesGoods::getIsTemp, false);

            queryWrapper.and(j -> {
                List<CesStockType> stockTypeList = list.stream().filter(t2 -> t2.getParentId().equals(t.getId())).collect(Collectors.toList());
                if (ObjectUtils.isNotEmpty(stockTypeList)) {
                    for (int z = 0; z < stockTypeList.size(); z++) {
                        j = j.or().eq(CesGoods::getGoodType, stockTypeList.get(z).getId());
                    }
                }
                j = j.or().eq(CesGoods::getGoodType, t.getId());
            });
            List<CesGoods> cesGoodsList = cesGoodsService.list(queryWrapper);
            vo.setList(cesGoodsList);
            voList.add(vo);
        });
        return Result.OK(voList);
    }

    /**
     * 对应酒店用户绑定会员卡信息
     *
     * @param memberCard
     * @return
     */
    @ApiOperation(value = "对应酒店用户绑定会员卡信息", notes = "对应酒店用户绑定会员卡信息")
    @GetMapping(value = "/memeber-card-info")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<BusMemberCard> getMemeberCard(BusMemberCard memberCard) {
        String tenantId = TenantContextHolder.getTenantId();
        String userId = ThirdSessionHolder.getUserId();
        LambdaQueryWrapper<BusMemberCard> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BusMemberCard::getUserId, userId);
        lambdaQueryWrapper.eq(BusMemberCard::getHotelId, memberCard.getHotelId()).last("limit 1");
        BusMemberCard busMemberCard = busMemberCardService.getOne(lambdaQueryWrapper);
        if (busMemberCard != null) {
            busMemberCard.setMarketMember(busMarketMemberService.getById(busMemberCard.getGradeId()));
        }
        return Result.ok(busMemberCard);
    }

    /**
     * 提交外卖订单
     *
     * @param mallOrderGoods
     * @return
     */
    @ApiOperation(value = "提交外卖订单", notes = "提交外卖订单")
    @PostMapping(value = "/save-goods-order")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    @Transactional(rollbackFor = Exception.class)
    public Result<BusMemberCard> saveGoodsOrder(@RequestBody MallOrderGoods mallOrderGoods) {
        String tenantId = TenantContextHolder.getTenantId();
        String userId = ThirdSessionHolder.getUserId();

        if (ObjectUtils.isEmpty(mallOrderGoods.getDetailList())) {
            return Result.error("订单商品列表不能为空");
        }
        if (mallOrderGoods.getIsBalancePay()) {
            if (StringUtils.isBlank(mallOrderGoods.getBalancePwd())) {
                return Result.error("请输入会员卡密码");
            }
            if (StringUtils.isBlank(mallOrderGoods.getMemberId())) {
                return Result.error("启用余额支付时，会员卡不能为空");
            }
            BusMemberCard busMemberCard = busMemberCardService.getById(mallOrderGoods.getMemberId());
            if (busMemberCard == null) {
                return Result.error("会员卡不存在");
            }
            if (!busMemberCard.getConsumePassword().equals(mallOrderGoods.getBalancePwd())) {
                return Result.error("会员卡密码不对");
            }
            if (busMemberCard.getBalance().compareTo(mallOrderGoods.getMoney()) < 0) {
                return Result.error("会员卡余额不够");
            }
            BusMemberBalanceLog busMemberBalanceLog = new BusMemberBalanceLog();
            busMemberBalanceLog.setMoney(mallOrderGoods.getMoney());
            busMemberBalanceLog.setMemberId(mallOrderGoods.getMemberId());
            busMemberBalanceLog.setHotelId(mallOrderGoods.getHotelId());
            busMemberBalanceLog.setPaymentMethod("");
            busMemberBalanceLog.setType(2);
            busMemberBalanceLog.setGiveMoney(BigDecimal.ZERO);
            busMemberBalanceLog.setPayMoney(BigDecimal.ZERO);
            busMemberBalanceLogService.saveBalance(busMemberBalanceLog);
        }

        mallOrderGoods.setTenantId(tenantId);
        mallOrderGoods.setMallUserId(userId);
        mallOrderGoods.setCreateTime(DateTime.now());
        mallOrderGoods.setPayStatus(0);
        mallOrderGoods.setStatus(1);
        mallOrderGoods.setPaymentMethod(1);
        mallOrderGoods.setIntegralPayMoney(BigDecimal.ZERO);
        String prefix = "WM";
        mallOrderGoods.setCode(randomNumber(prefix));
        mallOrderGoodsService.save(mallOrderGoods);
        mallOrderGoods.getDetailList().forEach(t -> {
            t.setHotelId(mallOrderGoods.getHotelId());
            t.setTenantId(mallOrderGoods.getTenantId());
            t.setOrderCode(mallOrderGoods.getCode());
        });
        mallOrderGoodsDetailService.saveBatch(mallOrderGoods.getDetailList());

        //创建业务消息信息
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getDelFlag, 0);
        lambdaQueryWrapper.eq(SysUser::getRelTenantIds, mallOrderGoods.getTenantId());
        List<SysUser> sysUsers = sysUserService.list(lambdaQueryWrapper);
        String userIds = "";
        for (SysUser sysUser : sysUsers) {
            userIds += sysUser.getUsername() + ",";
        }
        if (userIds.length() > 0) {
            MessageDTO messageDTO = new MessageDTO();
            messageDTO.setFromUser("");
            messageDTO.setToUser(userIds);
            messageDTO.setTitle("商城点餐订单");
            messageDTO.setContent("商城点餐订单");
            messageDTO.setCategory(CommonConstant.MSG_CATEGORY_2);
            sysBaseAPI.sendSysAnnouncement(messageDTO);
        }
        return Result.ok("提交成功");
    }

    /**
     * 酒店外卖订单列表
     * @param mallOrderGoods
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "酒店外卖订单列表", notes = "酒店外卖订单列表")
    @GetMapping(value = "/hotel-goods-order-list")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<IPage<MallOrderGoods>> getHotelGoodsOrderPageList(MallOrderGoods mallOrderGoods,
                                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                               HttpServletRequest req) {
        String tenantId = TenantContextHolder.getTenantId();
        String userId = ThirdSessionHolder.getUserId();
        LambdaQueryWrapper<MallOrderGoods> queryWrapper = QueryGenerator.initQueryWrapper(mallOrderGoods, req.getParameterMap()).lambda();
        queryWrapper.eq(MallOrderGoods::getTenantId, tenantId);
        queryWrapper.eq(MallOrderGoods::getMallUserId, userId);
        Page<MallOrderGoods> page = new Page<MallOrderGoods>(pageNo, pageSize);
        IPage<MallOrderGoods> pageList = mallOrderGoodsService.page(page, queryWrapper);
        pageList.getRecords().forEach(t -> {
            if (t.getStatus().equals(1)) {
                t.setStatusName("待发货");
            } else if (t.getStatus().equals(2)) {
                t.setStatusName("待收货");
            } else if (t.getStatus().equals(3)) {
                t.setStatusName("已完成");
            } else if (t.getStatus().equals(4)) {
                t.setStatusName("已拒绝");
            } else if (t.getStatus().equals(5)) {
                t.setStatusName("已取消");
            }
            BusHotel hotel = busHotelService.getById(t.getHotelId());
            if (hotel != null) {
                t.setHotelName(hotel.getName());
            }
            LambdaQueryWrapper<MallOrderGoodsDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(MallOrderGoodsDetail::getOrderCode, t.getCode());
            List<MallOrderGoodsDetail> list=mallOrderGoodsDetailService.list(lambdaQueryWrapper);
            if(ObjectUtils.isNotEmpty(list)){
                list.forEach(i->{
                    i.setGoodsInfo(cesGoodsService.getById(i.getGoodsId()));
                });
            }
            t.setDetailList(list);
        });
        return Result.OK(pageList);
    }

    /**
     * 通过id查询酒店外卖订单详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过id查询酒店外卖订单详情", notes = "通过id查询酒店外卖订单详情")
    @GetMapping(value = "/hotel-goods-order-info")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<MallOrderGoods> getHotelGoodsOrderInfo(@RequestParam(name = "id", required = true) String id) {
        MallOrderGoods mallOrderGoods = mallOrderGoodsService.getById(id);
        if (mallOrderGoods.getStatus().equals(1)) {
            mallOrderGoods.setStatusName("待发货");
        } else if (mallOrderGoods.getStatus().equals(2)) {
            mallOrderGoods.setStatusName("待收货");
        } else if (mallOrderGoods.getStatus().equals(3)) {
            mallOrderGoods.setStatusName("已完成");
        } else if (mallOrderGoods.getStatus().equals(4)) {
            mallOrderGoods.setStatusName("已拒绝");
        } else if (mallOrderGoods.getStatus().equals(5)) {
            mallOrderGoods.setStatusName("已取消");
        }
        BusHotel hotel = busHotelService.getById(mallOrderGoods.getHotelId());
        if (hotel != null) {
            mallOrderGoods.setHotelName(hotel.getName());
        }
        LambdaQueryWrapper<MallOrderGoodsDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MallOrderGoodsDetail::getOrderCode, mallOrderGoods.getCode());
        List<MallOrderGoodsDetail> list=mallOrderGoodsDetailService.list(lambdaQueryWrapper);
        if(ObjectUtils.isNotEmpty(list)){
            list.forEach(i->{
                i.setGoodsInfo(cesGoodsService.getById(i.getGoodsId()));
            });
        }
        mallOrderGoods.setDetailList(list);
        return Result.OK(mallOrderGoods);
    }

    /**
     * 获取入住订单费用账单(结账界面费用展示)
     * @param bookingOrderId
     * @return
     */
    @ApiOperation(value="获取入住订单费用账单(结账界面费用展示)", notes="获取入住订单费用账单(结账界面费用展示)")
    @RequestMapping(value = "/living-fees",method = RequestMethod.GET)
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<HashMap> getLivingOrderFees(String bookingOrderId) {
        if (bookingOrderId == null || bookingOrderId.isEmpty()) throw new JeecgBootException("参数错误");
        // 第二个参数不传默认是 未结账
        List<BusOrderFee> list = busRoomBookingOrdersService.getLivingOrderFee(bookingOrderId, null);
        HashMap<String, BigDecimal> obj = new HashMap<String, BigDecimal>();
        obj.put("xf", BigDecimal.ZERO);
        obj.put("sk", BigDecimal.ZERO);
        if (list != null && list.size() > 0) {
            List<BusOrderFee> xfList = list.stream().filter(t -> t.getFeeType().equals(1)).collect(Collectors.toList());
            if (xfList != null && xfList.size() > 0) {
                BigDecimal sum = BigDecimal.ZERO;
                for (BusOrderFee busOrderFee : xfList) {
                    sum = sum.add(busOrderFee.getMoney());
                }
                obj.put("xf", sum);
            }
            List<BusOrderFee> skList = list.stream().filter(t -> t.getFeeType().equals(2)).collect(Collectors.toList());
            if (skList != null && skList.size() > 0) {
                BigDecimal sum = BigDecimal.ZERO;
                for (BusOrderFee busOrderFee : skList) {
                    sum = sum.add(busOrderFee.getMoney());
                }
                obj.put("sk", sum);
            }
        }
        return Result.ok(obj);
    }

    /**
     * 单房一键结账
     * @param livingOrderId
     * @return
     */
    @ApiOperation(value="单房一键结账", notes="单房一键结账")
    @RequestMapping(value = "/living-settle-checkout",method = RequestMethod.POST)
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<Boolean> livingSettleBillCheckOut(@RequestBody List<BusOrderFee> fees,@RequestParam(name = "livingOrderId") String livingOrderId,@RequestParam(name = "hotelId") String hotelId) {
        if (fees != null && fees.size() > 0) {
            LambdaQueryWrapper<BusRoomPayType> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(BusRoomPayType::getHotelId, hotelId);
            List<BusRoomPayType> list = busRoomPayTypeService.list(lambdaQueryWrapper);
            if (list != null && list.size() > 0) {
                Optional<BusRoomPayType> optional = list.stream().filter(t -> t.getName().contains("现金")).findFirst();
                if (optional.isPresent()) {
                    fees.get(0).setPayType(optional.get().getId());
                } else {
                    fees.get(0).setPayType(list.get(0).getId());
                }
            }
        }
        Boolean isOk = busRoomBookingOrdersService.settleBillCheckOut(fees, livingOrderId);
        return Result.OK(isOk);
    }

    /**
     * 一键续住
     * @return
     */
    @ApiOperation(value="一键续住", notes="一键续住")
    @RequestMapping(value = "/continue-living",method = RequestMethod.POST)
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<Boolean> continueLiving(@RequestBody BusOrderFee fees,@RequestParam(name = "dueOutTime") @JsonFormat(pattern = "yyyy-MM-dd HH:mm")  @DateTimeFormat(pattern="yyyy-MM-dd HH:mm")  Date dueOutTime, @RequestParam(name = "livingOrderId") String livingOrderId ,@RequestParam(name = "hotelId") String hotelId) {
        LambdaQueryWrapper<BusRoomPayType> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BusRoomPayType::getHotelId, hotelId);
        fees.setPayType("");
        List<BusRoomPayType> list = busRoomPayTypeService.list(lambdaQueryWrapper);
        if (list != null && list.size() > 0) {
            Optional<BusRoomPayType> optional = list.stream().filter(t -> t.getName().contains("微信")).findFirst();
            if (optional.isPresent()) {
                fees.setPayType(optional.get().getId());
            } else {
                fees.setPayType(list.get(0).getId());
            }
        }
        Boolean isOk = busRoomBookingOrdersService.continueLiving(fees, dueOutTime, livingOrderId, hotelId);
        return Result.OK(isOk);
    }

    /**
     * 提交pos桌台点餐订单
     *
     * @param mallPosTableOrderGoods
     * @return
     */
    @ApiOperation(value = "提交pos桌台点餐订单", notes = "提交pos桌台点餐订单")
    @PostMapping(value = "/save-pos-table-goods-order")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    @Transactional(rollbackFor = Exception.class)
    public Result<String> savePosTableGoodsOrder(@RequestBody MallPosTableOrderGoods mallPosTableOrderGoods) {
        String tenantId = TenantContextHolder.getTenantId();
        String userId = ThirdSessionHolder.getUserId();

        if (ObjectUtils.isEmpty(mallPosTableOrderGoods.getDetailList())) {
            return Result.error("订单商品列表不能为空");
        }

        mallPosTableOrderGoods.setTenantId(tenantId);
        mallPosTableOrderGoods.setMallUserId(userId);
        mallPosTableOrderGoods.setCreateTime(DateTime.now());
        mallPosTableOrderGoods.setPayStatus(0);
        mallPosTableOrderGoods.setStatus(1);
        mallPosTableOrderGoods.setPaymentMethod(1);
        mallPosTableOrderGoods.setIntegralPayMoney(BigDecimal.ZERO);
        String prefix = "WM";
        mallPosTableOrderGoods.setCode(randomNumber(prefix));
        mallPosTableOrderGoodsService.save(mallPosTableOrderGoods);
        mallPosTableOrderGoods.getDetailList().forEach(t -> {
            t.setHotelId(mallPosTableOrderGoods.getHotelId());
            t.setTenantId(mallPosTableOrderGoods.getTenantId());
            t.setOrderCode(mallPosTableOrderGoods.getCode());
        });
        mallPosTableOrderGoodsDetailService.saveBatch(mallPosTableOrderGoods.getDetailList());

        //创建业务消息信息
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getDelFlag, 0);
        lambdaQueryWrapper.eq(SysUser::getRelTenantIds, mallPosTableOrderGoods.getTenantId());
        List<SysUser> sysUsers = sysUserService.list(lambdaQueryWrapper);
        String userIds = "";
        for (SysUser sysUser : sysUsers) {
            userIds += sysUser.getUsername() + ",";
        }
        if (userIds.length() > 0) {
            MessageDTO messageDTO = new MessageDTO();
            messageDTO.setFromUser("");
            messageDTO.setToUser(userIds);
            messageDTO.setTitle("商城桌台点餐订单");
            messageDTO.setContent("商城桌台点餐订单");
            messageDTO.setCategory(CommonConstant.MSG_CATEGORY_2);
            sysBaseAPI.sendSysAnnouncement(messageDTO);
        }
        return Result.ok("提交成功");
    }

    /**
     * 获取pos桌台详情
     * @param id
     * @return
     */
    @ApiOperation(value = "获取pos桌台详情", notes = "获取pos桌台详情")
    @GetMapping(value = "/pos-table-info")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<PosTable> getPosTableInfo(@RequestParam(name = "id") String id) {
        PosTable posTable = posTableService.getById(id);
        if (posTable != null) {
            PosType posType = posTypeService.getById(posTable.getPosTypeId());
            if (posType != null) {
                posTable.setTypeName(posType.getName());
            }
        }
        return Result.ok(posTable);
    }


    /**
     * pos桌台扫码点餐订单列表
     * @param mallPosTableOrderGoods
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "pos桌台扫码点餐订单列表", notes = "pos桌台扫码点餐订单列表")
    @GetMapping(value = "/pos-table-goods-order-list")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<IPage<MallPosTableOrderGoods>> getPosTableGoodsOrderPageList(MallPosTableOrderGoods mallPosTableOrderGoods,
                                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                    HttpServletRequest req) {
        String tenantId = TenantContextHolder.getTenantId();
        String userId = ThirdSessionHolder.getUserId();
        LambdaQueryWrapper<MallPosTableOrderGoods> queryWrapper = QueryGenerator.initQueryWrapper(mallPosTableOrderGoods, req.getParameterMap()).lambda();
        queryWrapper.eq(MallPosTableOrderGoods::getTenantId, tenantId);
        queryWrapper.eq(MallPosTableOrderGoods::getMallUserId, userId);
        Page<MallPosTableOrderGoods> page = new Page<MallPosTableOrderGoods>(pageNo, pageSize);
        IPage<MallPosTableOrderGoods> pageList = mallPosTableOrderGoodsService.page(page, queryWrapper);
        pageList.getRecords().forEach(t -> {
            if (t.getStatus().equals(1)) {
                t.setStatusName("待接单");
            } else if (t.getStatus().equals(2)) {
                t.setStatusName("已接单");
            } else if (t.getStatus().equals(3)) {
                t.setStatusName("已完成");
            } else if (t.getStatus().equals(4)) {
                t.setStatusName("已拒绝");
            } else if (t.getStatus().equals(5)) {
                t.setStatusName("已取消");
            }
            LambdaQueryWrapper<MallPosTableOrderGoodsDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(MallPosTableOrderGoodsDetail::getOrderCode, t.getCode());
            List<MallPosTableOrderGoodsDetail> list=mallPosTableOrderGoodsDetailService.list(lambdaQueryWrapper);
            if(ObjectUtils.isNotEmpty(list)){
                list.forEach(i->{
                    i.setGoodsInfo(cesGoodsService.getById(i.getGoodsId()));
                });
            }
            t.setDetailList(list);

            PosTable posTable=posTableService.getById(t.getPosTableId());
            if(posTable!=null) {
                t.setTableNo(posTable.getName());
            }
        });
        return Result.OK(pageList);
    }

    /**
     * 通过id查询pos桌台扫码点餐订单详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过id查询pos桌台扫码点餐订单详情", notes = "通过id查询pos桌台扫码点餐订单详情")
    @GetMapping(value = "/pos-table-goods-order-info")
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiLogin
    public Result<MallPosTableOrderGoods> getPosTableGoodsOrderInfo(@RequestParam(name = "id", required = true) String id) {
        MallPosTableOrderGoods mallPosTableOrderGoods = mallPosTableOrderGoodsService.getById(id);
        if (mallPosTableOrderGoods.getStatus().equals(1)) {
            mallPosTableOrderGoods.setStatusName("待接单");
        } else if (mallPosTableOrderGoods.getStatus().equals(2)) {
            mallPosTableOrderGoods.setStatusName("已接单");
        } else if (mallPosTableOrderGoods.getStatus().equals(3)) {
            mallPosTableOrderGoods.setStatusName("已完成");
        } else if (mallPosTableOrderGoods.getStatus().equals(4)) {
            mallPosTableOrderGoods.setStatusName("已拒绝");
        } else if (mallPosTableOrderGoods.getStatus().equals(5)) {
            mallPosTableOrderGoods.setStatusName("已取消");
        }
        LambdaQueryWrapper<MallPosTableOrderGoodsDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MallPosTableOrderGoodsDetail::getOrderCode, mallPosTableOrderGoods.getCode());
        List<MallPosTableOrderGoodsDetail> list=mallPosTableOrderGoodsDetailService.list(lambdaQueryWrapper);
        if(ObjectUtils.isNotEmpty(list)){
            list.forEach(i->{
                i.setGoodsInfo(cesGoodsService.getById(i.getGoodsId()));
            });
        }
        mallPosTableOrderGoods.setDetailList(list);

        PosTable posTable=posTableService.getById(mallPosTableOrderGoods.getPosTableId());
        if(posTable!=null) {
            mallPosTableOrderGoods.setTableNo(posTable.getName());
        }
        return Result.OK(mallPosTableOrderGoods);
    }

}
